package com.ipartek.formacion.migracion.ddbb;

import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.ipartek.formacion.migracion.dao.MySqlPersonaDAO;
import com.ipartek.formacion.migracion.interfaces.InterfacePersonaDAO;

/**
 * 
 * @author Fila3+1
 */
public class MySqlDAOFactory extends DAOFactory {
	// inicializo un DataSource (para utilizar el context.xml
	// Parametros configuracion base de datos
	private static String DRIVER_MYSQL = "com.mysql.jdbc.Driver";
	private static String DB_NAME;// = "migracion";
	private static String DB_PORT;// = "3306";
	private static String DB_USER;// = "root";
	private static String DB_PASS;// = "curso";
	private static String DB_SERVER;// = "localhost";
	private static String DB_URL;// = "jdbc:mysql://" + DB_SERVER + ":"
	// + DB_PORT + "/" + DB_NAME;

	private static final String PATH_LOG = "config/log4j.properties";
	private static final String PATH_CONFIG = "config/configuracion.properties";

	private static final Logger log = Logger.getLogger(MySqlDAOFactory.class);

	// Constructor
	// ************************************************************************
	public MySqlDAOFactory() {
		// Configuramos log4j
		PropertyConfigurator.configure(PATH_LOG);

		// Configuramos bbdd
		try {
			configDataBase();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Metodos
	// ************************************************************************

	// Conectar con la base de datos
	public static Connection conectar() throws Exception {
		Connection conexion = null; // Creamos un tipo connection
		try {
			Class.forName(DRIVER_MYSQL);

			// Define URL of database server for
			// database named mysql on the localhost
			// with the default port number 3306.
			// Get a connection to the database for a
			// user named root with a blank password.
			// This user is the default administrator
			// having full privileges to do anything.

			log.debug("Conectamos con la ddbb");

			conexion = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
			conexion.setAutoCommit(false);

			log.debug("Conectados con la ddbb " + DB_URL);
		} catch (ClassNotFoundException e) {
			log.error("ClassNotFoundException driver no encontrado "
					+ DRIVER_MYSQL);
		} catch (SQLException e) {
			while (e != null) {
				log.error("Message: " + e.getMessage() + "SQLState: "
						+ e.getSQLState() + "ErrorCode: " + e.getErrorCode());
				e = e.getNextException();
			}
		} catch (Exception e) {
			log.error("Exception general al conectar con la ddbb "
					+ e.getMessage());
		}
		log.debug("Devolvemos la conexion con la ddbb");
		return conexion;
	}

	// Desconectar con la base de datos
	public static void desconectar(Connection conexion) {
		if (conexion != null) {
			try {
				conexion.close();
			} catch (SQLException ex) {
				log.error("Exception general al desconectar con la ddbb "
						+ ex.getMessage());
			}
		}
	}

	// Desconectar con la base de datos
	public static void commit(Connection conexion) {
		if (conexion != null) {
			try {
				conexion.commit();
			} catch (SQLException ex) {
				log.error("Exception general al hacer commit con la ddbb "
						+ ex.getMessage());
			}
		}
	}

	// Desconectar con la base de datos
	public static void roolback(Connection conexion) {
		if (conexion != null) {
			try {
				conexion.rollback();
			} catch (SQLException ex) {
				log.error("Exception general al hacer rollback con la ddbb "
						+ ex.getMessage());
			}
		}
	}

	// Metodos que tengo que implementar al extender de DAOFActory
	// *************************************************************************
	@Override
	public InterfacePersonaDAO getInterfacePersonaDAO() {
		return new MySqlPersonaDAO("personas");
	}

	private void configDataBase() throws Exception {

		FileInputStream is = new FileInputStream(PATH_CONFIG);
		Properties prop = new Properties();
		prop.load(is);

		DB_SERVER = prop.getProperty("dbserver");
		DB_PORT = prop.getProperty("dbport");
		DB_NAME = prop.getProperty("database");
		DB_USER = prop.getProperty("dbuser");
		DB_PASS = prop.getProperty("dbpass");
		DB_URL = "jdbc:mysql://" + DB_SERVER + ":" + DB_PORT + "/" + DB_NAME;

	}
}
